/*
 * 组件注释
 * @Author: wuq-l
 * @Date: 2022-09-04 16:49:32
 * @LastEditors: machinist_wq
 * @LastEditTime: 2022-10-27 09:39:17
 * @Description:
 * 既往不恋！当下不杂！未来不迎！！！
 */
"use strict";
import { useState, useEffect, forwardRef, useImperativeHandle } from "react";
import { Space, Tag } from "antd";
import styles from "./index.less";

/*
 * 组件注释
 * create by wuqiong
 * creation time 2022/01/18
 * Tags 选中集合（筛选）
 * */

const { CheckableTag } = Tag;
const Index = forwardRef((props, ref) => {
  const {
    dataSource,
    onChange,
    checkedKeys,
    defaultCheckedKeys,
    single = false,
  } = props;
  const [selectedTags, setSelectedTags] = useState(defaultCheckedKeys || {});

  const handleChange = (tag, checked, key) => {
    let nextSelectedTags;
    if (single) {
      nextSelectedTags = checked ? tag : undefined;
    } else {
      nextSelectedTags = checked
        ? [...(selectedTags[key] || []), tag]
        : (selectedTags[key] || []).filter(t => t !== tag);
    }
    const allSelectedTags = { ...selectedTags, [key]: nextSelectedTags };

    // 如果checkedKeys有值 则内部不处理state的变化
    checkedKeys ?? setSelectedTags(allSelectedTags);

    onChange &&
      onChange({ key, checked, checkedKeys: allSelectedTags, tagValue: tag });
  };

  useEffect(() => {
    if (checkedKeys && Object.is(checkedKeys, selectedTags)) {
      setSelectedTags(checkedKeys);
    }
  }, [checkedKeys]);

  useImperativeHandle(ref, () => ({
    selectedTags,
    setSelectedTags,
    handleChange,
  }));

  return (
    <div className={`${styles.checkableTags} checkableTags`}>
      {dataSource.map((item, idx) => {
        const { fieldNames = {}, data, title, key } = item;

        return (
          <div
            key={key}
            style={{ marginBottom: dataSource.length - 1 !== idx ? 16 : 0 }}>
            {title ? (
              <span className={`${styles.title} title`}>{title}:</span>
            ) : null}
            <div className={`${styles.checkableTag} checkableTag`}>
              <Space>
                {data.map(tag => {
                  const tagKey = tag[fieldNames.value] || tag.key;
                  const tagName = tag[fieldNames.label] || tag.name;
                  return (
                    <CheckableTag
                      key={tagKey}
                      checked={
                        single
                          ? selectedTags[key] === tagKey
                          : (selectedTags[key] || []).includes(tagKey)
                      }
                      onChange={checked => handleChange(tagKey, checked, key)}>
                      {tagName}
                    </CheckableTag>
                  );
                })}
              </Space>
            </div>
          </div>
        );
      })}
    </div>
  );
});
Index.defaultProps = {
  // 数据格式
  dataSource: [
    {
      title: "表单类型",
      key: "assetType",
      // fieldNames 和antd 一样
      // fieldNames: {},
      data: [
        {
          name: "问卷调查",
          key: "1",
        },
        {
          name: "数据填报",
          key: "2",
        },
      ],
    },
  ],
  single: false,
  onChange: values => console.log(values),
};

export default Index;
